package com.dmw.dao.impl;

import com.dmw.dao.IUserDao;
import com.dmw.pojo.User;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class IUserDaoImpl implements IUserDao {
    @Autowired
    private HibernateTemplate template;


    public void addUser(User user) {
        this.template.save(user);
    }

    public void alterUser(User user) {
        this.template.update(user);
    }

    public void removeUser(User user) {
        this.template.delete(user);
    }

    public User findUserById(Integer userId) {
        User user = this.template.get(User.class, userId);
        return user;
    }

    public List<User> findUserByNameByHQL(String userName) {
        Session session = this.template.getSessionFactory().getCurrentSession();
        Query query = session.createQuery(" from User where userName =:abc");
              query = query.setString("abc" , userName);
        return query.list();
    }

    public List<User> findUserByNameBySQL(String userName) {
        Session session = this.template.getSessionFactory().getCurrentSession();
        Query query = session.createSQLQuery(" SELECT u.user_id , u.user_name , u.real_name  FROM `t_user` u where  u.user_name =? ")
                .addEntity(User.class)
                .setString(0,userName);
        return query.list();
    }

    public List<User> findUserByNameByCriteria(String userName) {
        Session session = this.template.getSessionFactory().getCurrentSession();
        Criteria criteria = session.createCriteria(User.class);
        criteria.add( Restrictions.eq("userName" , userName));
        return criteria.list();
    }
}
